package cn.itsource.hrm.controller;

import cn.itsource.hrm.util.FastDfsApiOpr;
import cn.itsource.util.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenyuqi
 * @version v1.0.0
 * @date 2020/5/23
 */
@RestController
public class FileController {
    /**
     * 文件上传
     * @return
     */
    @RequestMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        try {
            //文件内容
            byte[] bytes = file.getBytes();
            //获取到文件名
            String originalFilename = file.getOriginalFilename();
            originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //文件的扩展名
            String extName = null;
            String fileId = FastDfsApiOpr.upload(bytes, extName);
            return AjaxResult.me().setSuccess(true).setMessage("上传成功").setResultObj(fileId);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败"+e.getMessage());
        }




    }

    /**
     * 文件下载
     * @param fileID fileID = /group1/xxx/xxx/xxxx
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileID") String fileID, HttpServletResponse response){
        try {
            //group1/xxx/xxx/xxxx
            fileID = fileID.substring(1);
            int index = fileID.indexOf("/");

            //group1
            String groupName = fileID.substring(0,index);

            // xxx/xxx/xxxx
            String fileName = fileID.substring(index+1);
            byte[] bytes = FastDfsApiOpr.download(groupName, fileName);
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
